/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sims.gui.salesperson;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import javax.smartcardio.Card;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import sims.entity.Product;
import sims.manager_SalesPerson.Function;

/**
 *
 * @author vanthanh
 */
public class OrderSell extends javax.swing.JPanel {

    /**
     * Creates new form OrderSell
     */
    DefaultTableModel model = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int i, int i1) {
            return false;
        }
    };
    ArrayList<String> arrUpdateItem = new ArrayList<String>();

    public OrderSell() {
        initComponents();
        Calendar cal = Calendar.getInstance();
        lbDay.setText(String.valueOf(cal.get(Calendar.DATE)));
        lbMonth.setText(String.valueOf(cal.get(Calendar.MONTH +1)));
        lbYear.setText(String.valueOf(cal.get(Calendar.YEAR)));
        String[] column = {"STT", "ItemID", "Item Name", "Unit", "Price", "Amount", "Cost"};
        model.setColumnIdentifiers(column);
        jTable_OrderSell.setModel(model);
    }
    String username;
    public OrderSell(String userName) {
        initComponents();
        this.username = userName;
        Function fun = new Function();
//        int userId = fun.getUserId("thanhtv");
        Calendar cal = Calendar.getInstance();
        lbUserName.setText("thanhtv");
        lbDay.setText(String.valueOf(cal.get(Calendar.DATE)));
        lbMonth.setText(String.valueOf(cal.get(Calendar.MONTH)+1));
        lbYear.setText(String.valueOf(cal.get(Calendar.YEAR)));
        String[] column = {"STT", "ItemID", "Item Name", "Unit", "Price", "Amount", "Cost"};
        model.setColumnIdentifiers(column);
        jTable_OrderSell.setModel(model);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtItemName = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txtAmount = new javax.swing.JTextField();
        bn_Ok = new javax.swing.JButton();
        bn_del = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable_OrderSell = new javax.swing.JTable();
        bn_Submit = new javax.swing.JButton();
        bn_Cancel = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lbTotal = new javax.swing.JLabel();
        lbUserName = new javax.swing.JLabel();
        lbDay = new javax.swing.JLabel();
        lbMonth = new javax.swing.JLabel();
        lbYear = new javax.swing.JLabel();

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText(" Order  Sell");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Datetime :");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("User Name:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel4.setText("ItemName:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setText("Amount:");

        bn_Ok.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bn_Ok.setText("OK");
        bn_Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bn_OkActionPerformed(evt);
            }
        });

        bn_del.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bn_del.setText("Delete");
        bn_del.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bn_delActionPerformed(evt);
            }
        });

        jTable_OrderSell.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable_OrderSell);

        bn_Submit.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bn_Submit.setText("Submit");
        bn_Submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bn_SubmitActionPerformed(evt);
            }
        });

        bn_Cancel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bn_Cancel.setText("Cancel");
        bn_Cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bn_CancelActionPerformed(evt);
            }
        });

        jLabel6.setText("-");

        jLabel7.setText("-");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel8.setText("Total:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(37, 37, 37)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lbDay, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lbMonth, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lbYear, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(lbUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(151, 151, 151)
                        .addComponent(bn_Submit)
                        .addGap(31, 31, 31)
                        .addComponent(bn_Cancel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtItemName, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bn_Ok)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bn_del))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(lbTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7)
                    .addComponent(lbDay)
                    .addComponent(lbMonth)
                    .addComponent(lbYear))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(lbUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtItemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bn_Ok)
                    .addComponent(bn_del)
                    .addComponent(jLabel5))
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(lbTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bn_Submit)
                    .addComponent(bn_Cancel))
                .addGap(28, 28, 28))
        );
    }// </editor-fold>//GEN-END:initComponents
int stt = 0;
    private void bn_OkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bn_OkActionPerformed

        if ("".equals(txtItemName.getText()) || "".equals(txtAmount.getText())) {
            JOptionPane.showMessageDialog(this, "Item name and Amount must not null!");
        }else if (!txtAmount.getText().matches("[1-9][0-9]*")) {
            JOptionPane.showMessageDialog(this, "Amount must is number!");
        } else {
            boolean checkIdtrung = true;
            for (int i = 0; i < jTable_OrderSell.getRowCount(); i++) {
                if (txtItemName.getText().equals(jTable_OrderSell.getValueAt(i, 2).toString())) {
                    checkIdtrung = false;
                    JOptionPane.showMessageDialog(this, "Item name existed");
                    break;
                }
            }
            if (checkIdtrung) {
                Function fun = new Function();
                ArrayList<Product> arrProduct = new ArrayList<Product>();
                int amount = Integer.parseInt(txtAmount.getText());
                arrProduct = fun.get_All_Item();
                boolean flag = true;
                
                for (Product product : arrProduct) {
                    if (txtItemName.getText().equals(product.getProductName())) {
                        flag = false;
                        if (amount <= product.getQuantity()) {
                            stt++;
                            Object[] row = {stt, product.getId(), product.getProductName(), product.getUnit(), product.getPrice(), amount, product.getPrice() * amount};
                            model.addRow(row);
                            jTable_OrderSell.setModel(model);
                            txtAmount.setText("");
                            txtItemName.setText("");
                            float total = 0;
                            for (int i = 0; i < jTable_OrderSell.getRowCount(); i++) {
                                total += Float.parseFloat(jTable_OrderSell.getValueAt(i, 6).toString());
                            }
                            lbTotal.setText(String.valueOf(total));
                            String updateItem = "update item set quantityAvailable= " + (product.getQuantity() - amount) + " where itemId = '" + product.getId() + "'";
                            arrUpdateItem.add(updateItem);
                            break;
                        } else {
                            JOptionPane.showMessageDialog(this, "Amount is not enough");
                        }
                    }
                }
                if (flag) {
                    JOptionPane.showMessageDialog(this, "Item name not exist ");
                }
            }
        }

    }//GEN-LAST:event_bn_OkActionPerformed

    private void bn_delActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bn_delActionPerformed
        if (jTable_OrderSell.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "select item need delete");
        } else {
            stt--;
            int x = jTable_OrderSell.getSelectedRow();
            model.removeRow(x);
            arrUpdateItem.remove(x);
            float total = 0;
            for (int i = 0; i < jTable_OrderSell.getRowCount(); i++) {
                total += Float.parseFloat(jTable_OrderSell.getValueAt(i, 6).toString());
            }
            lbTotal.setText(String.valueOf(total));
        }
        this.repaint();
    }//GEN-LAST:event_bn_delActionPerformed

    private void bn_SubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bn_SubmitActionPerformed

        Function fun = new Function();
        ArrayList<Product> arrProduct = fun.get_All_Item();
        ArrayList<String> arrInsertOrder = new ArrayList<String>();
        ArrayList<String> arrInsertOrder_Item = new ArrayList<String>();

        String day = lbDay.getText();
        String month = lbMonth.getText();
        String year = lbYear.getText();
        // sau thay bang username
        int userId = fun.getUserId("thanhtv");
        //String userId = lbUserName.getText();
       
        float total = 0;
        for (int i = 0; i < jTable_OrderSell.getRowCount(); i++) {
            total += Float.parseFloat(jTable_OrderSell.getValueAt(i, 6).toString());
        }
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        String datetime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "";
        if ("".equals(lbUserName.getText()) || "".equals(lbDay.getText()) || "".equals(lbMonth.getText()) || "".equals(lbYear.getText())) {
            JOptionPane.showMessageDialog(this, "datetime and userId must not null!!!");
        } else {
            if (!day.matches("[1-9][0-9]*") || !month.matches("[1-9][0-9]*") || !year.matches("[1-9][0-9]*")) {
                JOptionPane.showMessageDialog(this, "datetime must is number!!!");
            } else if (Integer.parseInt(day) > 31 || Integer.parseInt(month) > 12 || Integer.parseInt(year) > cal.get(Calendar.YEAR)) {
                JOptionPane.showMessageDialog(this, "datetime not valid");
            } else {
                if (jTable_OrderSell.getRowCount() > 0) {
                    String insertOrder = "insert into orders values ('" + datetime + "','" + userId + "','sell','successed'," + total + ")";
                    arrInsertOrder.add(insertOrder);
                    fun.runBath(arrInsertOrder);
                    int OrderId = fun.getOrderId(userId);
                    for (int i = 0; i < jTable_OrderSell.getRowCount(); i++) {
                        String itemId = jTable_OrderSell.getValueAt(i, 1).toString();
                        int Amount = Integer.parseInt(jTable_OrderSell.getValueAt(i, 5).toString());
                        float price = Float.parseFloat(jTable_OrderSell.getValueAt(i, 4).toString());
                        String insertOrderItem = "insert into order_item values(" + OrderId + ",'" + itemId + "'," + Amount + "," + price + ")";
                        arrInsertOrder_Item.add(insertOrderItem);
                    }
                    fun.runBath(arrUpdateItem);
                    fun.runBath(arrInsertOrder_Item);
                    JOptionPane.showMessageDialog(this, "Submit successfull");
                    stt=0;
                    int rows = model.getRowCount();
                    for (int i = rows - 1; i >= 0; i--) {
                        model.removeRow(i);
                    }
                    lbTotal.setText("");
                } else {
                    JOptionPane.showMessageDialog(this, "don't have Item purchased!!!");
                    
                }
            }
        }
    }//GEN-LAST:event_bn_SubmitActionPerformed

    private void bn_CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bn_CancelActionPerformed
        if (jTable_OrderSell.getRowCount() > 0){
            int cancel =JOptionPane.showConfirmDialog(this, "are you sure want cancel ?",null,JOptionPane.YES_NO_OPTION);
            if(cancel== JOptionPane.OK_OPTION )
            {
                int rows = model.getRowCount();
                    for (int i = rows - 1; i >= 0; i--) {
                        model.removeRow(i);
                    }
                    lbTotal.setText("");
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "don't have Item purchased!!!");
        }
    }//GEN-LAST:event_bn_CancelActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bn_Cancel;
    private javax.swing.JButton bn_Ok;
    private javax.swing.JButton bn_Submit;
    private javax.swing.JButton bn_del;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable_OrderSell;
    private javax.swing.JLabel lbDay;
    private javax.swing.JLabel lbMonth;
    private javax.swing.JLabel lbTotal;
    private javax.swing.JLabel lbUserName;
    private javax.swing.JLabel lbYear;
    private javax.swing.JTextField txtAmount;
    private javax.swing.JTextField txtItemName;
    // End of variables declaration//GEN-END:variables
}
